<?php

namespace App\Http\Controllers\admin;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use DB;
class GoodsController extends Controller
{
	static public function getGg(){
		$data = DB::table('cate') -> select(DB::raw("*,concat(path,',',id) as paths"))->orderBy('paths') -> get();
    	foreach ($data as $k => $v){
    		$l = substr_count($v['path'],',');
    		$data[$k]['name'] = str_repeat('|----', $l).$v['name'];
    	}
    	return $data;
	}


	//商品添加页面
   public function getAdd()
   {
   		
        return view('admin.goods.add',['data'=>self::getGg()]);
   }

   //商品添加到数据库
   public function postInsert(Request $request)
   {	
   		// $this::chuli($request);
   		// 上传图片处理
   		if($request -> hasFile('gphoto') && $request -> hasFile('gbigphoto')){
   			//创建上传文件名
   			$tmp = md5(time()+rand(10000,99999));
   			//读取文件后缀
   			$hz = $request -> file('gphoto') -> getClientOriginalExtension();
   			$name = $tmp.'.'.$hz;
   			$arr = ['jpg','png','gif','jpeg'];
   			
   			
   		}
   		//检测是否填写数据
   		 $this->validate($request,[
            'gname'=> 'required',
            'gpath'=> 'required',
            'gscprice'=> 'required',
            'ghyprice'=>'required',
            'gsum' =>'required',
            'gsum' =>'required',
            'gjf' => 'required',
            'gphoto'=>'required',
            'gbigphoto'=>'required',
            ],[
                'gname.required'=>'商品名不能为空',
                'gpath.required'=>'商品类别不能为空',
                'gphoto.required'=>'请上传图片',
                'gbigphoto.required'=>'请上传图片(大图)',
                'gscprice.required'=>'市场价格不能为空',
                'ghyprice.required'=>'会员价格不能为空', 
                'gsum.required'=>'商品数量不能为空',
                'gjf.required'=>'购买积分不能为空（商品价格）',

            ]);

   		 //限制商品价格和数量不能小于 1 
   		if($request->input('gsum') < 1){
   			return back() -> with('error','商品数量不能小于1');
   		}
   		 if($request->input('gscprice') <1 ){
        return back() -> with('error','市场价格不能小于1');
      }

       if($request->input('ghyprice') <1){
        return back() -> with('error','会员价格不能小于1');
      }
   		
   		 //处理数据
   		$data = $request->except('_token');
   		$data['gphoto'] = $name;
   		$data['gbigphoto']= $name;
   		$data['starttime'] = time();
   		$cate = DB::table('cate')->where('id',$data['gpath'])->first();
   		$data['gpath'] = $cate['path'];
   		
   		//插入数据库
   		$res =	DB::table('goods') -> insert($data);
   		// 处理结果
   		if($res){
        if(in_array($hz, $arr)){
          $request -> file('gphoto')->move('./smallgoods',$name);
          $request -> file('gbigphoto')->move('./biggoods',$name);
        }
   			return redirect('/admin/goods/index') -> with('success','添加成功');
   		}else{
   			return back() -> with('error','添加失败');
   		}
   }

   //上架商品页面
   public function getIndex(Request $request){
      $search = $request-> input('search','');
      $count = $request -> input('count',10);

   	$data = DB::table('goods')->where('gstatus','1')->where('gname','like','%'.$search.'%')->paginate($count);

   	 return view('admin.goods.index',['data'=>$data,'request'=>$request->all()]);
   	 
   }

   //低库存商品页面
   public function getLess(Request $request){
    $search = $request-> input('search','');
      $count = $request -> input('count',10);
   	$data = DB::table('goods')->where('gstatus','1')->where('gsum','<','30')->where('gname','like','%'.$search.'%')->paginate($count);
   	return view('admin.goods.index',['data'=>$data,'request'=>$request->all()]);
   }

   //下架商品页面
   public function getOut(Request $request){
    $search = $request-> input('search','');
      $count = $request -> input('count',10);
   $data = DB::table('goods')->where('gstatus','2')->where('gname','like','%'.$search.'%')->paginate($count);
 
   	return view('admin.goods.index',['data'=>$data,'request'=>$request->all()]);
   }


   //修改商品页面
   public function getEdit($gid){
   	// dd($gid);
   	$data = DB::table('goods')->where('gid',$gid)->first();
   	return view('admin.goods.edit',['data'=>$data,'fenlei'=>self::getGg()]);
   }

   //插入修改数据
   public function postUpdate(Request $request)
   {
   		
   	//检测是否填写数据
       $this->validate($request,[
            'gname'=> 'required',
            'gscprice'=> 'required',
            'ghyprice'=>'required',
            'gsum' =>'required',
            'gsum' =>'required',
            'gjf' => 'required',
            ],[
                'gname.required'=>'商品名不能为空',
                'gscprice.required'=>'市场价格不能为空',
                'ghyprice.required'=>'会员价格不能为空', 
                'gsum.required'=>'商品数量不能为空',
                'gjf.required'=>'购买积分不能为空（商品价格）',

            ]);

     //限制商品价格和数量不能小于 1 
      if($request->input('gsum') < 1){
        return back() -> with('error','商品数量不能小于1');
      }
      if($request->input('gscprice') <1 ){
        return back() -> with('error','市场价格不能小于1');
      }

       if($request->input('ghyprice') <1){
        return back() -> with('error','会员价格不能小于1');
      }

      $id = $request -> only('id');
      $goods = DB::table('goods')->where('gid',$id)->first();
      $data = $request->except('id','_token');
      // 上传图片处理
      if($request -> hasFile('gphoto') && $request -> hasFile('gbigphoto')){
        //创建上传文件名
        $tmp = md5(time()+rand(10000,99999));
        //读取文件后缀
        $hz = $request -> file('gphoto') -> getClientOriginalExtension();
        $name = $tmp.'.'.$hz;
        $arr = ['jpg','png','gif','jpeg'];
        
         
       $data['gphoto'] = $name;
       $data['gbigphoto']= $name;
      }
   		// $this::chuli($request);
      // dd($data);
   		
   		// dd($data['gpath']);
     

   		$cate = DB::table('cate')->where('id',$data['gpath'])->first();
      // dd($cate);
      if($request->input('gpath')==''){
        $data['gpath']= $goods['gpath'];
      }else{
        $data['gpath']= $cate['path'];
      }
      
   		$data['lsxgtime'] = time();
   		//插入数据库
   		$res =	DB::table('goods') -> where('gid',$id)-> update($data);

      // dd($res);
   		// 处理结果
   		if($res >0){
        if($request -> hasFile('gphoto') && $request -> hasFile('gbigphoto')){
             if(in_array($hz, $arr)){
          $request -> file('gphoto')->move('./smallgoods',$name);
          $request -> file('gbigphoto')->move('./biggoods',$name);
           }
        }
   			return redirect('/admin/goods/index') -> with('success','修改成功');
   		}else{
   			return back() -> with('error','修改失败');
   		}
   }


   //下架商品 处理数据
   public function getXjgoods($id){
      //查询 该商品状态
      $data = DB::table('goods')->where('gid',$id)->first();
      if($data['gstatus'] == 1){
      $res = DB::table('goods')->where('gid',$id) ->update(['gstatus'=>2]);
          if($res>0)
        {
            return redirect('/admin/goods/out') -> with('success','下架成功');
        }else{
            return back() -> with('error','下架失败');
        }
      }

      if($data['gstatus'] == 2){
       $res = DB::table('goods')->where('gid',$id) ->update(['gstatus'=>1]);
        if($res>0)
        {
            return redirect('/admin/goods/index') -> with('success','下架成功');
        }else{
            return back() -> with('error','下架失败');
        }
      }
    }


    //删除商品(只能删除下架商品)
    public function getDel($id){
       $res =  DB::table('goods')->where('gid',$id)->delete();
        if($res>0)
        {
            return redirect('/admin/goods/out') -> with('success','删除成功');
        }else{
            return back() -> with('error','删除失败');
        }
    }
 }

